const DB = require('../../config/DB')
const {
    Op
} = require('sequelize')
const { uMd5, uPutToken } = require('../utils/index')
// 建立关联
DB.favorite.belongsTo(DB.note)
DB.favorite.belongsTo(DB.user)
DB.like.belongsTo(DB.user)
DB.like.belongsTo(DB.note)
DB.note.belongsTo(DB.user)
DB.fans.belongsTo(DB.user)
DB.news.belongsTo(DB.note)
class UserController {
    // 已读
    async readNews(ctx) {
        const {
            newsId
        } = ctx.request.body
        await DB.news.update({
            read: 1
        }, {
            where: {
                id: newsId
            }
        })
        global.Response.success(ctx)
    }
    // 删除
    async deleteNews(ctx) {
        const {
            newsId
        } = ctx.request.body
        await DB.news.destroy({
            where: {
                id: newsId
            }
        })
        global.Response.success(ctx)
    }
    // 获取系统通知
    async getNewsBySystem(ctx) {
        const {
            userId
        } = ctx.query
        const news = await DB.news.findAll({
            where: {
                to: userId,
                type: 3
            },
            include: [{
                model: DB.note,
                // attributes: ['id', 'name', 'avatar', 'brief']
            }],
            order: [
                ['createdAt', 'DESC']
            ]
        })
        global.Response.success(ctx, undefined, news)
    }
    // 获取消息评论/回复/@
    async getNews(ctx) {
        const {
            userId
        } = ctx.query
        const news = await DB.news.findAll({
            where: {
                to: userId,
                type: {
                    [Op.or]: [1, 2], // 评论或回复
                }
            },
            order: [
                ['createdAt', 'DESC']
            ]
        })
        for (let row of news) {
            const user = await DB.user.findOne({
                where: {
                    id: row.get('from')
                },
                attributes: ['id', 'name', 'avatar']
            })
            row.dataValues.user = user
        }
        global.Response.success(ctx, undefined, news)
    }
    // 获取关注关系
    async getRelationShip(ctx) {
        let {
            userId, currentUserId
        } = ctx.query
        userId = Number(userId)
        currentUserId = Number(currentUserId)
        const isFocus = await DB.fans.findOne({
            where: {
                userId: userId,
                fansId: currentUserId
            }
        })
        const isFans = await DB.fans.findOne({
            where: {
                userId: currentUserId,
                fansId: userId
            }
        })
        const data = {
            userId,
            currentUserId,
            isFocus: isFocus ? true : false,
            isFans: isFans ? true : false,
            both: isFocus && isFans ? true : false
        }
        global.Response.success(ctx, undefined, data)
    }
    // 关注
    async toFocus(ctx) {
        const {
            userId,
            fansId,
            cancel = false
        } = ctx.request.body
        let msg = '关注成功'
        if (cancel) {
            await DB.fans.destroy({
                where: {
                    userId,
                    fansId
                }
            })
            msg = "取消关注成功"
        } else {
            await DB.fans.findOrCreate({
                where: {
                    userId,
                    fansId
                }, defaults: {
                    createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                    updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
                }
            })
        }
        global.Response.success(ctx, msg)
    }
    // 根据作者ID获取对应点赞的笔记
    async getLikeByUser(ctx) {
        // 参数
        let {
            page = 1, size = 10, userId
        } = ctx.query
        page = Number(page)
        size = Number(size)
        const {
            count,
            rows
        } = await DB.like.findAndCountAll({
            offset: (page - 1) * size,
            limit: size,
            order: [
                ['id', 'DESC']
            ],
            where: {
                userId
            },
            include: [{ // 关联 DB.like.belongsTo(DB.note)
                model: DB.note,
                include: [
                    {
                        model: DB.user,
                        attributes: ['id', 'name', 'avatar']
                    }
                ]
            }]
        })
        for (let row of rows) {
            if (row.note) {
                row.dataValues.carousel = row.note.carousel
                row.dataValues.user = row.note.user
            }
        }
        const data = {
            rows,
            meta: {
                size, // 每页条目
                count: count, // 条目总数
                page: page, // 当前页数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)
    }
    // 根据作者ID获取对应收藏的笔记
    async getFavoriteByUser(ctx) {
        // 参数
        let {
            page = 1, size = 10, userId
        } = ctx.query
        page = Number(page)
        size = Number(size)
        const {
            count,
            rows
        } = await DB.favorite.findAndCountAll({
            offset: (page - 1) * size,
            limit: size,
            order: [
                ['id', 'DESC']
            ],
            where: {
                userId
            },
            include: [{ // 关联 DB.like.belongsTo(DB.note)
                model: DB.note,
                include: [
                    {
                        model: DB.user,
                        attributes: ['id', 'name', 'avatar']
                    }
                ]
            }]
        })
        for (let row of rows) {
            if (row.note) {
                row.dataValues.carousel = row.note.carousel
                row.dataValues.user = row.note.user
            }
        }
        const data = {
            rows,
            meta: {
                size, // 每页条目
                count: count, // 条目总数
                page: page, // 当前页数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)
    }
    // 根据作者ID获取对应笔记
    async getNoteByUser(ctx) {
        // 参数
        let {
            page = 1, size = 10, userId
        } = ctx.query
        page = Number(page)
        size = Number(size)
        const {
            count,
            rows
        } = await DB.note.findAndCountAll({
            offset: (page - 1) * size,
            limit: size,
            order: [
                // ['status', 'DESC'],
                ['id', 'DESC']
            ],
            where: {
                userId
            },
            include: [{
                model: DB.user,
                attributes: ['id', 'name', 'avatar']
            }]
        })
        const data = {
            rows,
            meta: {
                size, // 每页条目
                count: count, // 条目总数
                page: page, // 当前页数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)
    }
    // 注册
    async registerUser(ctx) {
        const {
            phone,
            password,
            name,
        } = ctx.request.body
        const same = await DB.user.findOne({
            where: { phone }
        })
        if (same) {
            global.Response.exist(ctx, '该手机号码已注册~')
        } else {
            const user = await DB.user.create({
                phone,
                password: uMd5(password),
                name,
                createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
            })
            const data = {
                user: {
                    userId: user.id,
                    name: user.name,
                    phone: user.phone,
                },
                token: uPutToken(user.id)
            }
            global.Response.success(ctx, '注册成功', data)
        }
    }
    // 密码登录
    async loginByPassword(ctx) {
        const {
            phone,
            password
        } = ctx.request.body
        const user = await DB.user.findOne({
            where: {
                phone,
                password: uMd5(password)
            }
        })
        if (user) {
            // 检测用户是否被冻结
            const status = user.get('status')
            if(status === 0 ) {
                global.Response.fail(ctx, '该用户被冻结，请联系管理员')
                return false
            }
            let lastLoginAt = await user.get('updatedAt')
            // 更新登录时间
            user.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
            await user.save()
            const data = {
                user: {
                    userId: user.id,
                    name: user.name,
                    phone: user.phone,
                    avatar: user.avatar,
                    brief: user.brief,
                    lastLoginAt
                },
                token: uPutToken(user.id)
            }
            global.Response.success(ctx, '登录成功', data)
        } else {
            global.Response.fail(ctx, '账号或密码错误')
        }
    }
    // 获取用户信息
    async getUserInfo(ctx) {
        const {
            userId
        } = ctx.query
        const user = await DB.user.findByPk(userId, {
            attributes: {
                exclude: ['password']
            }
        })
        // 我的粉丝
        const fans = await DB.fans.count({
            where: {
                userId
            }
        })
        // 我的关注
        const focus = await DB.fans.count({
            where: {
                fansId: userId
            },
            include: [{
                model: DB.user,
                attributes: ['id', 'name', 'avatar', 'brief']
            }]
        })
        // 我的获赞与收藏
        const note = await DB.note.findAll({
            where: {
                userId
            },
        })
        let like = 0, favorite = 0
        for (let row of note) {
            like += row.like
            favorite += row.favorite
        }
        user.dataValues.fans = fans
        user.dataValues.focus = focus
        user.dataValues.like = like
        user.dataValues.favorite = favorite
        global.Response.success(ctx, undefined, user)
    }
    // 我的关注
    async getUserFocus(ctx) {
        const {
            userId
        } = ctx.query
        const focus = await DB.fans.findAll({
            where: {
                fansId: userId
            },
            include: [{
                model: DB.user,
                attributes: ['id', 'name', 'avatar', 'brief']
            }]
        })
        // 查询是否互相关注
        for (let row of focus) {
            let both = await DB.fans.findOne({
                where: {
                    userId,
                    fansId: row.userId
                }
            })
            if (both) row.dataValues.both = true
        }
        global.Response.success(ctx, undefined, focus)
    }
    // 我的粉丝
    async getUserFans(ctx) {
        const {
            userId
        } = ctx.query
        const fans = await DB.fans.findAll({
            where: {
                userId
            }
        })
        for (let row of fans) {
            let user = await DB.user.findOne({
                where: { id: row.fansId },
                attributes: ['id', 'name', 'avatar', 'brief']
            })
            row.dataValues.user = user
            // 查询是否互相关注
            let both = await DB.fans.findOne({
                where: {
                    userId: row.fansId,
                    fansId: userId
                }
            })
            if (both) row.dataValues.both = true
        }
        global.Response.success(ctx, undefined, fans)
    }
    // 加载我的收藏
    async loadFavorites(ctx) {
        const {
            id: userId
        } = ctx.query
        const fans = await DB.favorite.findAll({
            where: {
                userId
            },
        })
        // for (let row of fans) {
        //     likeNum += row.like
        //     favoriteNum += row.favorite
        // }
        // 联表 user

        global.Response.success(ctx, undefined, fans)
    }
    async loadLikes(ctx) {

    }
    async loadBrowses(ctx) {
    }
    // 修改手机号
    async editPhone(ctx) {
        const {
            id,
            phone,
        } = ctx.request.body
        const same = await DB.user.findOne({
            where: {
                phone
            }
        })
        if (same) {
            global.Response.exist(ctx, '手机号重复')
            return false
        }
        await DB.user.update({
            phone
        }, {
            where: {
                id,
            }
        })
        global.Response.success(ctx, '更新成功')
    }
    // 修改密码
    async editPassword(ctx) {
        const {
            id,
            password,
        } = ctx.request.body
        await DB.user.update({
            password: uMd5(password)
        }, {
            where: {
                id,
            }
        })
        global.Response.success(ctx, '更新成功')
    }
    // 编辑信息
    async editInfo(ctx) {
        const {
            id,
            name,
            brief,
            avatar,
            cover
        } = ctx.request.body

        await DB.user.update({
            name,
            brief,
            avatar,
            cover,
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
        }, {
            where: {
                id,
            }
        }) // return [0] [1]
        global.Response.success(ctx, '更新成功')
    }
    async searchUser(ctx) {
    }
}

module.exports = new UserController
